/**************************************************
 * Project Name         [JavaEE_XML]
 * File Name            [StudentUtil.java]
 * Creation Date        [08-15-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 **************************************************/
package pkg_exam.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class StudentUtil {

	private static final String fileName = "src/pkg_exam/Exam.xml";

	/**
	 * Load XML Document
	 * 
	 * @return
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws IOException
	 */
	public static Document getDocument() throws ParserConfigurationException,
			SAXException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse(new File(fileName));
		return document;
	}

	/**
	 * Write to XML Document
	 * 
	 * @param document
	 * @throws TransformerException
	 * @throws FileNotFoundException
	 */
	public static void writeToXML(Document document)
			throws FileNotFoundException, TransformerException {
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer();

		Properties props = transformer.getOutputProperties();
		props.setProperty(OutputKeys.ENCODING, "UTF-8");
		props.setProperty(OutputKeys.METHOD, "xml");
		transformer.setOutputProperties(props);

		transformer.transform(new DOMSource(document), new StreamResult(
				new File(fileName)));

	}
}
